package com.eastcom.groovy.task

import com.eastcom.groovy.config.ExternConfig
import com.eastcom.groovy.config.GroovyScript
import com.eastcom.groovy.config.TaskConfig
import com.eastcom.groovy.context.TaskContext
import com.eastcom.groovy.tools.file.GroovyUtil;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.quartz.Job
import org.quartz.JobExecutionContext
import org.quartz.JobExecutionException

/**
 * Created by yuanyue on 2014-07-31.
 */
class Task implements Job {
	/** 任务id */
	String jobId;

	/** 任务名称 */
	String jobName;

	/** 任务分组 */
	String jobGroup;

	/** 任务状态 0禁用 1启用 2删除*/
	String jobStatus;

	/** 任务运行时间表达式 */
	String cronExpression;

	/** 任务描述 */
	String desc;

	String rootPath;
	TaskConfig taskConfig
	private static Log logger = LogFactory.getLog(Task.class)
	Object doWork() {
		logger.debug("jobId["+jobId+"]开始！")
		Thread.currentThread().setName(jobId)
		ExternConfig extern = taskConfig.extern
		GroovyScript executorScript
		if(extern.executor.groovyScriptInfo != null){
			executorScript = extern.executor.groovyScriptInfo
		}else{
			executorScript = new GroovyScript()
			executorScript.scriptFileRootPath = rootPath
			executorScript.scriptFileName = extern.executor.executorClass
			executorScript.param = jobId
		}
		Class<?> clazz = GroovyUtil.loadScriptClass(executorScript)
		logger.debug("script class["+clazz+"]")
		GroovyObject clazzObj = (GroovyObject)clazz.newInstance()
		logger.debug("脚本"+clazzObj)
		logger.debug("开始执行脚本。。。")
		Object o = clazzObj.invokeMethod("doJob",(String)executorScript.param)
		logger.debug("脚本执行结果："+o)
		return o
	}

	@Override
	void execute(JobExecutionContext context) throws JobExecutionException {
		logger.debug("任务继续进行。。。")
		Task scheduleJob = (Task) context.getMergedJobDataMap().get("scheduleJob");
		try {
			scheduleJob.doWork()
		}catch (Exception e){
			e.printStackTrace()
		}
		logger.debug("任务已经做完。。。")
	}
}
